import smbus2 as smbus
import time
import csv
from datetime import datetime
import os

# 初始化 I2C 总线
bus = smbus.SMBus(1)
address = 0x5A

def read_temp():
    data = bus.read_i2c_block_data(address, 0x07, 3)
    temp = (data[1] << 8) | data[0]
    temp = temp * 0.02 - 273.15
    return temp

# 只有在直接运行此脚本时才执行温度记录循环
if __name__ == "__main__":
    # 检查文件是否存在，如果不存在则创建并写入表头
    if not os.path.exists('data_temp.csv'):
        with open('data_temp.csv', 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(["Timestamp", "Temperature (°C)"])
        print("创建新的数据文件 data_temp.csv")

    print("开始记录温度数据到 data_temp.csv...")
    print("按 Ctrl+C 停止记录")

    try:
        while True:
            # 读取温度
            temperature = read_temp()
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            # 打印到控制台
            print(f"{timestamp} - 温度: {temperature:.2f} °C")

            # 追加到 CSV 文件
            with open('data_temp.csv', 'a', newline='') as file:
                writer = csv.writer(file)
                writer.writerow([timestamp, f"{temperature:.2f}"])

            # 等待 1 秒
            time.sleep(1)

    except KeyboardInterrupt:
        print("\n记录已停止。数据已追加到 data_temp.csv 中")
